const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 生成简单的token（实际项目中应使用更安全的JWT）
function generateToken(adminInfo) {
  const timestamp = Date.now()
  const randomStr = Math.random().toString(36).substr(2, 9)
  return `${adminInfo._id}_${timestamp}_${randomStr}`
}

exports.main = async (event, context) => {
  const { username, password } = event
  
  console.log('管理员登录尝试:', { username, timestamp: new Date() })
  
  try {
    // 验证管理员账号
    const adminResult = await db.collection('admins').where({
      username: username,
      password: password, // 实际应用中需要加密存储和验证
      status: 'active'
    }).get()
    
    if (adminResult.data.length > 0) {
      const adminInfo = adminResult.data[0]
      
      // 生成token
      const token = generateToken(adminInfo)
      const expireTime = new Date(Date.now() + 24 * 60 * 60 * 1000) // 24小时后过期
      
      // 保存token到数据库
      await db.collection('admin_tokens').add({
        data: {
          adminId: adminInfo._id,
          token: token,
          expireTime: expireTime,
          createTime: new Date(),
          lastUsed: new Date()
        }
      })
      
      // 更新管理员最后登录时间
      await db.collection('admins').doc(adminInfo._id).update({
        data: {
          lastLoginTime: new Date()
        }
      })
      
      console.log('管理员登录成功:', { adminId: adminInfo._id, username })
      
      return {
        success: true,
        token: token,
        adminInfo: {
          _id: adminInfo._id,
          username: adminInfo.username,
          role: adminInfo.role,
          avatar: adminInfo.avatar
        }
      }
    } else {
      console.log('管理员登录失败: 用户名或密码错误', { username })
      return {
        success: false,
        message: '用户名或密码错误'
      }
    }
  } catch (error) {
    console.error('管理员登录错误:', error)
    return {
      success: false,
      error: error.message,
      message: '登录失败，请稍后重试'
    }
  }
}